import fs from 'node:fs'

let uid = 0

export class DataBase {
  static read() {
    const fileData = fs.readFileSync('./data.json')
    try {
      return JSON.parse(fileData)
    } catch {
      console.log('数据库读取异常')
    }
  }

  static query(id) {
    const data = this.read()
    return data.find((item) => item.id === id)
  }

  static add(person) {
    const data = this.read()
    data.push({ ...person, id: uid++ })

    try {
      fs.writeFileSync('./data.json', JSON.stringify(data))
    } catch {
      console.log('数据库写入异常')
    }
  }

  static update(person) {
    const data = this.read()
    try {
      fs.writeFileSync(
        './data.json',
        JSON.stringify(
          data.map((item) => {
            if (item.id === person.id) {
              return person
            }

            return item
          })
        )
      )
    } catch {
      console.log('数据库写入异常')
    }
  }

  static delete(id) {
    const data = this.read()
    try {
      fs.writeFileSync(
        './data.json',
        JSON.stringify(data.filter((item) => item.id !== id))
      )
    } catch {
      console.log('数据库写入异常')
    }
  }
}
